package app.quiz;

import app.quiz.util.Constants;
import app.quiz.util.HTMLWriter;
import org.antlr.stringtemplate.StringTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/14/12
 * Time: 3:04 PM
 */
public abstract class GenericPatternServlet extends HttpServlet {


    protected String htmlFileName;
    protected StringTemplate htmlTemplate;

    @Override
    public void init() throws ServletException {
        super.init();

        setHtmlFileName();

        if (htmlFileName != null) {
            try {
                htmlTemplate = HTMLWriter.getHTMLTemplate(htmlFileName);
            } catch (IOException e) {
                throw new ServletException("Can't read from file " + htmlFileName + ".", e);
            }
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (doSomeInitialProcessing(request, response)) {

            response.setContentType(Constants.CONTENT_TYPE);

            PrintWriter printWriter = response.getWriter();

            fillInHTMLTemplate(request, response);

            printWriter.print(htmlTemplate);
        }
    }

    protected void fillInHTMLTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected boolean doSomeInitialProcessing(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        return true;
    }


    protected abstract void setHtmlFileName();

}
